const { src, dest, series, parallel } = require('gulp')
const swig = require('gulp-swig')
const data = require('gulp-data')
const rename = require('gulp-rename')
const eslint = require('gulp-eslint')
const gulpIf = require('gulp-if')
var map = require('map-stream')
var fs = require('fs')
var readline = require('readline')

var _ = require('lodash')
const { dateModal } = require('./gulp_data.js')

// 多名称
// 首字母大写
// 全大写大写
function setNameCase (obj) {
  obj.vm.camelCaseName = _.lowerFirst(obj.vm.name)
  obj.vm.startCaseName = _.join(_.split(_.startCase(obj.vm.name), ' '), '')
  obj.vm.PascalCaseName = _.capitalize(obj.vm.name)
  obj.vm.UnderScoreCaseName = _.toUpper(_.snakeCase(obj.vm.name))
  return obj
}

setNameCase(dateModal)
// console.log(dateModal)

function isFixed (file) {
  return file.eslint != null && file.eslint.fixed // 过滤只经过format的文件，不用format的，fixed为false
}

const createVm = () => {
  console.log('创建VM')
  console.log('手动复制粘贴以下内容')
  console.log('E:\\020work\\turn-right-pc-vue\\turn-right-vuepc-v4\\src\\viewModels\\viewModels.js')
  console.log(`import ${dateModal.vm.startCaseName}VM from 'SRC/viewModels/${dateModal.vm.startCaseName}/${dateModal.vm.startCaseName}VM'`)
  return src('gulp_tem/vm/tem_vm/*.js', { base: 'gulp_tem' })
    .pipe(data(dateModal))
    .pipe(swig())
    .pipe(eslint({ fix: true }))
    .pipe(eslint.format())
    .pipe(eslint.failAfterError())
    .pipe(rename({
      dirname: '/vm/' + dateModal.vm.startCaseName,
      basename: dateModal.vm.startCaseName,
      suffix: 'VM',
      extname: '.js'
    }))
    .pipe(dest('dist'))
}

const createVuex = () => {
  console.log('开始创建state')
  console.log('手动复制粘贴以下内容')
  console.log('E:\\020work\\turn-right-pc-vue\\turn-right-vuepc-v4\\src\\store\\index.js')
  console.log(`import ${dateModal.vm.camelCaseName} from './modules/${dateModal.vm.camelCaseName}'`)
  return src('gulp_tem/vuex/tem_vuex/**.js', { base: 'gulp_tem' })
    .pipe(data(dateModal))
    .pipe(swig())
    .pipe(eslint({ fix: true }))
    .pipe(eslint.format())
    .pipe(eslint.failAfterError())
    .pipe(rename({
      dirname: '/vuex/' + dateModal.vm.name,
      extname: '.js'
    }))
    // .pipe(gulpIf(isFixed, dest('dist')))  // 只输出被format的文件
    .pipe(dest('dist'))
}

const copyPage = () => {
  console.log('开始复制page基础文件')
  return src(['gulp_tem/page/tem_page/*.html', 'gulp_tem/page/tem_page/*.js'], { base: 'gulp_tem' })
    .pipe(eslint({ fix: true }))
    .pipe(eslint.format())
    .pipe(eslint.failAfterError())
    .pipe(rename({
      dirname: dateModal.vm.name
    }))
    .pipe(dest('dist'))
}

const configIndexPage = () => {
  console.log('开始自定义page index信息')
  return src('gulp_tem/page/tem_page/*.vue', { base: 'gulp_tem' })
    .pipe(data(dateModal))
    .pipe(swig())
    .pipe(rename({
      dirname: dateModal.vm.name,
      extname: '.vue'
    }))
    .pipe(dest('dist'))
}

const configSecondPage = () => {
  console.log('开始自定义page second信息')
  return src('gulp_tem/page/tem_page/components/*.vue', { base: 'gulp_tem' })
    .pipe(data(dateModal))
    .pipe(swig())
    .pipe(eslint({ fix: true }))
    // .pipe(eslint.format())
    .pipe(rename({
      dirname: dateModal.vm.name + '/components/',
      basename: dateModal.vm.startCaseName,
      suffix: 'Page',
      extname: '.vue'
    }))
    .pipe(dest('dist'))
}

const createApi = () => {
  console.log('创建api')
  console.log('手动复制粘贴以下内容')
  console.log(`import { get${dateModal.vm.startCaseName}, add${dateModal.vm.startCaseName}, edit${dateModal.vm.startCaseName}, delete${dateModal.vm.startCaseName}  } from 'SRC/service/${dateModal.vm.startCaseName}'`)
  return src('gulp_tem/service/tem_api/*.js', { base: 'gulp_tem' })
    .pipe(data(dateModal))
    .pipe(swig())
    .pipe(eslint({ fix: true }))
    .pipe(eslint.format())
    .pipe(eslint.failAfterError())
    .pipe(rename({
      dirname: '/service/' + dateModal.vm.camelCaseName,
      extname: '.js'
    }))
    .pipe(dest('dist'))
}

const exportApi = () => {
  return src('dist/service/**' + dateModal.vm.camelCaseName + '/**', { base: 'dist/service' })
    .pipe(dest('src/service'))
}

const exportPage = () => {
  return src('dist/' + dateModal.vm.camelCaseName + '/**', { base: 'dist' })
    .pipe(dest('src/pages'))
}
const exportVm = () => {
  return src('dist/vm/**', { base: 'dist/vm' })
    .pipe(dest('src/viewModels'))
}
const exportVuex = () => {
  return src('dist/vuex/**', { base: 'dist/vuex' })
    .pipe(dest('src/store/modules'))
}

const writeApi = async () => {
  // const text = `export const ${dateModal.vm.startCaseName} = '/${dateModal.vm.startCaseName}'` + ` \/\/${dateModal.vm.note}`
  const text = `\/\/ ${dateModal.vm.default}` +
  `
export const get${dateModal.vm.startCaseName} = '/get${dateModal.vm.startCaseName}'
export const add${dateModal.vm.startCaseName} = '/add${dateModal.vm.startCaseName}'
export const edit${dateModal.vm.startCaseName} = '/edit${dateModal.vm.startCaseName}'
export const delete${dateModal.vm.startCaseName} = '/delete${dateModal.vm.startCaseName}'
`
  fs.readFile('src/service/api.js', function (error, data) {
    if (error) {
      console.log('读取文件失败了')
    } else {
      fs.writeFile('src/service/api.js', data.toString() + '\r\n' + text, function (error) {
        if (error) {
          console.log('写入失败')
        } else {
          console.log('api写入成功了')
        }
      })
    }
  })
}

const writeVm = async () => {
  const text = `import ${dateModal.vm.startCaseName}VM from 'SRC/viewModels/${dateModal.vm.startCaseName}/${dateModal.vm.startCaseName}VM'`
  const text1 = `${dateModal.vm.startCaseName}VM`

  var fileName = 'src/viewModels/viewModels.js'
  var fileTempName = 'src/viewModels/viewModels.tem'
  fs.writeFileSync(fileTempName, '')
  var fRead = fs.createReadStream(fileName)
  var fWrite = fs.createWriteStream(fileTempName)

  var objReadline = readline.createInterface({
    input: fRead,
    // output: fWrite,
    terminal: true
  })
  let index = 1
  let key = 1
  let insert = false
  objReadline.on('line', (line) => {
    key++
    if (line === '') {
      if (index === 1) {
        fWrite.write(text)
        fWrite.write('\n')
        fWrite.write('\n')

        index++
      } else {
        fWrite.write('\n')
        index++
      }
    } else {
      if (insert && line.toString().indexOf(',') === -1) {
        fWrite.write(line)
        fWrite.write(',')
        fWrite.write('\n')
        fWrite.write('  ')
        fWrite.write(text1)
        fWrite.write('\n')
        insert = false
      } else if (line.toString().indexOf('export default {') !== -1) {
        console.log(key)
        insert = true
        fWrite.write(line)
        fWrite.write('\n')
      } else {
        fWrite.write(line)
        fWrite.write('\n')
      }
    }
  })
  objReadline.on('close', () => {
    console.log('readline close...')
    const data = fs.readFileSync(fileTempName)
    fs.writeFileSync(fileName, data.toString())

    fs.unlinkSync(fileTempName)
  })
}

const writeVuex = async () => {
  const text = `import ${dateModal.vm.camelCaseName} from './modules/${dateModal.vm.camelCaseName}'`
  const text1 = `${dateModal.vm.camelCaseName}`

  var fileName = 'src/store/index.js'
  var fileTempName = 'src/store/index.tem'
  fs.writeFileSync(fileTempName, '')
  var fRead = fs.createReadStream(fileName)
  var fWrite = fs.createWriteStream(fileTempName)

  var objReadline = readline.createInterface({
    input: fRead,
    // output: fWrite,
    terminal: true
  })
  let index = 1
  let key = 1
  let insert = false
  objReadline.on('line', (line) => {
    key++
    if (line === '') {
      if (index === 1) {
        fWrite.write(text)
        fWrite.write('\n')
        fWrite.write('\n')

        index++
      } else {
        fWrite.write('\n')
        index++
      }
    } else {
      if (insert && line.toString().indexOf(',') === -1) {
        fWrite.write(line)
        fWrite.write(',')
        fWrite.write('\n')
        fWrite.write('    ')
        fWrite.write(text1)
        fWrite.write('\n')
        insert = false
      } else if (line.toString().indexOf('modules: {') !== -1) {
        console.log(key)
        insert = true
        fWrite.write(line)
        fWrite.write('\n')
      } else {
        fWrite.write(line)
        fWrite.write('\n')
      }
    }
  })
  objReadline.on('close', () => {
    console.log('readline close...')
    const data = fs.readFileSync(fileTempName)
    fs.writeFileSync(fileName, data.toString())

    fs.unlinkSync(fileTempName)
  })
}

const createPage = series(copyPage, configIndexPage, configSecondPage)
const createMvvm = parallel(createVm, createVuex, createPage)

const writeMvvm = series(writeVm, writeVuex)
const exportMvvm = series(exportVuex, exportVm, exportPage, writeVm, writeVuex)

module.exports = {
  createApi,
  exportApi,
  writeApi,
  createVm,
  exportVm,
  writeVm,
  createVuex,
  exportVuex,
  writeVuex,
  createPage,
  exportPage,
  exportMvvm,
  createMvvm,
  writeMvvm
}

// module.exports = {
//   createVm,
//   copyPage,
//   createPage,
//   createVuex,
//   createApi,
//   exportVuex,
//   exportVm,
//   exportPage,
//   exportMvvm,
//   configIndexPage,
//   writeApi,
//   writeVm,
//   writeVuex,
//   createMvvm
// }
